import ApiService from './api';
import { LoginRequest, LoginResponse, User } from '../types';

// 认证服务
export class AuthService {
  // 登录
  static async login(credentials: LoginRequest): Promise<LoginResponse> {
    const response = await ApiService.post<{ data: LoginResponse }>('/admin/auth/login', credentials);

    // 从嵌套的data字段中提取登录响应数据
    const loginData = response.data;

    // 保存用户信息和token
    if (loginData.token) {
      ApiService.setAuthToken(loginData.token);
      localStorage.setItem('admin_user', JSON.stringify(loginData.user));
      localStorage.setItem('admin_permissions', JSON.stringify(loginData.permissions));
    }

    return loginData;
  }

  // 登出
  static async logout(): Promise<void> {
    try {
      await ApiService.post('/admin/auth/logout');
    } catch (error) {
      console.error('Logout error:', error);
    } finally {
      // 清除本地存储
      ApiService.clearAuthToken();
      localStorage.removeItem('admin_permissions');
    }
  }

  // 获取当前用户信息
  static async getCurrentUser(): Promise<User> {
    const response = await ApiService.get<{ data: User }>('/admin/auth/me');
    return response.data;
  }

  // 刷新token
  static async refreshToken(): Promise<string> {
    const response = await ApiService.post<{ data: { token: string } }>('/admin/auth/refresh');

    if (response.data.token) {
      ApiService.setAuthToken(response.data.token);
    }

    return response.data.token;
  }

  // 修改密码
  static async changePassword(data: {
    oldPassword: string;
    newPassword: string;
  }): Promise<void> {
    await ApiService.post('/admin/auth/change-password', data);
  }

  // 重置密码
  static async resetPassword(email: string): Promise<void> {
    await ApiService.post('/admin/auth/reset-password', { email });
  }

  // 验证token有效性
  static async validateToken(): Promise<boolean> {
    try {
      await this.getCurrentUser();
      return true;
    } catch (error) {
      return false;
    }
  }

  // 获取本地存储的用户信息
  static getStoredUser(): User | null {
    const userStr = localStorage.getItem('admin_user');
    return userStr ? JSON.parse(userStr) : null;
  }

  // 获取本地存储的权限信息
  static getStoredPermissions(): string[] {
    const permissionsStr = localStorage.getItem('admin_permissions');
    return permissionsStr ? JSON.parse(permissionsStr) : [];
  }

  // 获取认证token
  static getAuthToken(): string | null {
    return localStorage.getItem('admin_token');
  }

  // 检查是否已登录
  static isLoggedIn(): boolean {
    const token = this.getAuthToken();
    return !!token && !!this.getStoredUser();
  }
}

export default AuthService;
